package com.shenhan.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author shenhan
 * @Date: 2020/6/13 13:01
 * @Description: 自旋锁
 */
public class SpinLockDemo {
    AtomicReference<Thread> mylock = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> lock");
        while (!mylock.compareAndSet(null, thread)) {

        }
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> unlock");
        mylock.compareAndSet(thread, null);
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo mylock = new SpinLockDemo();
        new Thread(() -> {
            mylock.lock();
            try {
                TimeUnit.SECONDS.sleep(5L);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                mylock.unlock();
            }
        }, "T1").start();
        TimeUnit.SECONDS.sleep(1L);
        new Thread(() -> {
            mylock.lock();
            try {
                TimeUnit.SECONDS.sleep(1L);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                mylock.unlock();
            }
        }, "T2").start();
    }
}
